package top.cyixlq.chat.view;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.LinkedList;
import java.util.List;

import top.cyixlq.chat.R;
import top.cyixlq.chat.entity.MessageBean;

public class ChatMessageAdapter extends RecyclerView.Adapter<ChatMessageAdapter.ChatMessageViewHolder> {

    private final List<MessageBean> mData = new LinkedList<>();

    @NonNull
    @Override
    public ChatMessageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        final View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.item_chat_message, viewGroup, false);
        return new ChatMessageViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull ChatMessageViewHolder viewHolder, int i) {
        final MessageBean item = mData.get(i);
        if (item == null) return;
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) viewHolder.chatView.getLayoutParams();
        LinearLayout.LayoutParams nickNameParams = (LinearLayout.LayoutParams) viewHolder.tvNickName.getLayoutParams();
        if (item.isReceive()) {
            params.gravity = Gravity.START;
            nickNameParams.gravity = Gravity.START;
            viewHolder.chatView.setBubbleColor(0xff9933ff);
            viewHolder.chatView.setLook(BubbleLayout.Look.LEFT);
        } else {
            params.gravity = Gravity.END;
            nickNameParams.gravity = Gravity.END;
            viewHolder.chatView.setBubbleColor(0xff3399ff);
            viewHolder.chatView.setLook(BubbleLayout.Look.RIGHT);
        }
        viewHolder.tvMessage.setText(item.getContent());
        viewHolder.tvNickName.setText(item.getNickName());
    }

    public void addData(MessageBean msg) {
        this.mData.add(msg);
        this.notifyItemInserted(this.mData.size());
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    static class ChatMessageViewHolder extends RecyclerView.ViewHolder {

        TextView tvNickName;
        TextView tvMessage;
        BubbleLayout chatView;

        public ChatMessageViewHolder(@NonNull View itemView) {
            super(itemView);
            tvNickName = itemView.findViewById(R.id.tvNickName);
            tvMessage = itemView.findViewById(R.id.tvMessage);
            chatView = itemView.findViewById(R.id.chatView);
        }
    }
}
